<template>
	<view class="flex flex-column page">
		<view class="map-container">
			<view id="container" class="map-container" v-if="showMap"></view>
			<image src="@/static/icons/location.png" class="center-icon" mode="scaleToFill" />
			<view class="location-icon" :class="{ 'location-icon-loading': positionLoading }" @tap="getCurrentPosition">
				<uni-icons :type="positionLoading ? 'loop' : 'paperplane-filled'" size="20"
					color="var(--xl-primary)"></uni-icons>
			</view>
		</view>
		<view class="flex flex-center p-4 grid-gap-4">
			<input id="searchInput" v-model="keyword" type="text" class="bg-white rounded-4 p-4 flex-1" placeholder="搜索地点"
				confirm-type="search" @confirm="searchNearBy">
			<button class="btn-primary" :disabled="confirmDisabled" @tap="confirm">确定</button>
		</view>
		<scroll-view scroll-y class="flex-1 overflow-hidden">
			<view class="flex flex-column grid-gap-4 p-4" id="output">
				<view class="flex flex-center bg-white p-4 rounded-4 grid-gap-2" v-for="(item, index) in poiList"
					:key="index" @tap="selecedEvent(item, index)">
					<view class="flex-1 flex flex-column grid-gap-1">
						<text class="font-weight-500">{{ item.name }}</text>
						<text class="h9 text-placeholder">{{ item.address }}</text>
					</view>
					<uni-icons type="checkbox-filled" color="var(--xl-success)" v-if="seleced === index"></uni-icons>
					<uni-icons type="circle" color="var(--xl-grey)" v-else></uni-icons>
				</view>
			</view>
		</scroll-view>
		<view class="pb-safe-area"></view>
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick, computed,onBeforeUnmount } from "vue";
import { onLoad } from '@dcloudio/uni-app';
import { useMap } from "@/utils/map";
import { $EventName } from "@/utils/const/env";
let map: any, mapContainer: any, PlaceSearch: any;
const event = ref('');
const loading = ref(false);
const showMap = ref(false);
const location = ref({
	latitude: 0,
	longitude: 0,
	address: ''
});
const keyword = ref('');
const seleced = ref<number>();
const poiList = ref([]);
const selecedEvent = (item: any, index: number) => {
	seleced.value = index;
	location.value.latitude = item.location.lat;
	location.value.longitude = item.location.lng;
}
const confirmDisabled = computed(() => {
	return !(location.value.latitude && location.value.longitude);
})
const confirm = () => {
	uni.$emit(event.value, location.value);
	uni.navigateBack();
}
const initAMap = () => {
	showMap.value = true;
	nextTick(() => {
		map.usePlugin('PlaceSearch').then((instance: any) => {
			PlaceSearch = instance;
			PlaceSearch.setType('汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施');
		}).catch((err: any) => { });
		map.createMap("container").then((res: any) => {
			mapContainer = res;
			res.on('complete', () => {
				mapContainer.on('click', (e: any) => {
					mapContainer.setCenter([e.lnglat.lng, e.lnglat.lat]);
				});
				mapContainer.on('moveend', () => {
					if (loading.value) { return; }
					loading.value = true;
					const center = mapContainer.getCenter();
					location.value.latitude = center.lat;
					location.value.longitude = center.lng;
					map.getAddress([center.lng, center.lat]).then((result: any) => {
						const formattedAddress = result.formattedAddress;
						const addressComponent = result.addressComponent;
						location.value.province = addressComponent.province;
						location.value.city = addressComponent.city || addressComponent.province;
						location.value.area = addressComponent.district;
						location.value.street = addressComponent.township;
						location.value.address_detail = formattedAddress
							.replace(addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township, '');
						PlaceSearch.setCity(addressComponent.adcode);
						PlaceSearch.setPageSize(50)
						nextTick(() => {
							searchNearBy();
						});
						loading.value = false;
					}).catch((err: any) => {
						loading.value = false;
						console.log(err);
					})
				});
				getCurrentPosition();
			});
		}).catch((err: any) => {
			console.log(err);
		});
	})
}
const positionLoading = ref(false);
const getCurrentPosition = () => {
	if (positionLoading.value) { return; }
	positionLoading.value = true;
	map.getCurrentPosition().then((result: any) => {
		mapContainer && mapContainer.setCenter([result.position.lng, result.position.lat]);
	}).catch((err: any) => {
		console.log(err);
	}).finally(() => {
		positionLoading.value = false;
	})
}
const searchNearBy = () => {
	seleced.value = undefined;
	PlaceSearch.searchNearBy(keyword.value, [location.value.longitude, location.value.latitude], 200, (status: string, result: any) => {
		if (status == 'complete' && result.info === 'OK') {
			poiList.value = result.poiList.pois;
		} else {
			poiList.value = [];
		}
	});
}
const useInitMap = () => {
	map = useMap(() => {
		initAMap();
	});
}
onLoad((options: any) => {
	event.value = options.event;
	if (options.latitude && options.longitude) {
		location.value.latitude = options.latitude;
		location.value.longitude = options.longitude;
	}
	useInitMap();
	uni.$once($EventName.WEBCONFIG_READY, useInitMap)
});
onBeforeUnmount(() => {
	// #ifdef H5
	mapContainer && mapContainer.destroy();
	// #endif
	uni.$off($EventName.WEBCONFIG_READY, useInitMap);
});
</script>

<style lang="scss" scoped>
.page {
	height: calc(100vh - var(--window-top));
}

.map-container {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 40vh;
	position: relative;
}

.center-icon {
	width: 30px;
	height: 29px;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, calc(-50% - 14.5px));
	z-index: 999;
}

.location-icon {
	position: absolute;
	right: 10px;
	bottom: 10px;
	z-index: 999;
	width: 40px;
	height: 40px;
	background-color: var(--xl-white);
	border-radius: 50%;
	box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
	display: flex;
	justify-content: center;
	align-items: center;
}

.location-icon-loading {
	animation: rotate 3s linear infinite;
}
</style>
